//A Cache implement the LRU algorithms
jsx3.Class.defineClass(
        "ux.megatron.LRUCache",
        jsx3.lang.Object,
        null,
        function (cache,cache_prototype) {
			//configurations
			var CONFIG = {
				poolSize:10
			}
			
			//object cache pool
			var POOL = {
				
			}
			
			cache_prototype.init = function(config){
				this.jsxsuper();
				CONFIG = extendObj(CONFIG,config);
			}
			
			cache_prototype.set = function(key,obj){
				var oldKey = getCacheKeyByObjKey(POOL,key);
				if(oldKey != null)
					delete POOL[oldKey];
				
				if(getPoolSize(POOL) >= CONFIG.poolSize){
					//exceeded the size of object pool,discards one object least recently used
					var deleteKey = getLRUCacheKey(POOL);
					if(deleteKey != null)
						delete POOL[deleteKey];
				}
				
				var cacheKey = new Date().getTime();
				var cacheWrapper = {"key":key,"realObj":obj,"_$LRUCACHETIMESTAMP$_":cacheKey};
				POOL[cacheKey] = cacheWrapper;

			}
			
			cache_prototype.get = function(key){
				var cacheKey = getCacheKeyByObjKey(POOL,key);
				if(cacheKey != null){
					POOL[cacheKey]['_$LRUCACHETIMESTAMP$_'] = new Date().getTime();
					return POOL[cacheKey]["realObj"];
				}
					
				return null;
			}
			
			cache_prototype.remove = function(key){
				var ret = null;
				var cacheKey = getCacheKeyByObjKey(POOL,key);
				if(cacheKey != null){
                    /* @JSC :: begin DEBUG */
					console.log('LRU Cache found old cache obj for key:'+key);
                    /* @JSC :: end */
					ret = POOL[cacheKey];
					delete POOL[cacheKey];
				}
				return ret;
			}
			
			cache_prototype.clearPool = function(){
				POOL = new Object();
			}
			
			//helper functions
			var extendObj = function(tar,org){
				for(var prop in org){
					tar[prop] = org[prop];
				}
				return tar;
			}
			
			var getCacheKeyByObjKey = function(pool,key){
				for(var cachekey in pool){
					if(pool[cachekey]['key'] == key)
						return cachekey;
				}
				return null;
			}
			
			var getPoolSize = function(pool){
				var size = 0;
				for(var prop in pool){
					size ++;
				}
				return size;
			}
			
			var getLRUCacheKey = function(pool){
				var now = new Date().getTime();
				var distance = 0;
				var cachekey = null;
				for(var ckey in pool){
					var timeStamp = pool[ckey]['_$LRUCACHETIMESTAMP$_'];
					if(now - timeStamp > distance){
						distance = now - timeStamp;
						cacheKey = ckey;
					}						
				}
				return cacheKey;
				
			}
			
});